<template>
  <div class="layout-container">
    <!-- 上方菜单栏 -->
    <header class="layout-header">
      <div class="header-content">
        <div class="logo">
          <h1>XX医院综合信息平台</h1>
        </div>
        <nav class="navigation">
          <el-menu
            mode="horizontal"
            :default-active="activeMenu"
            class="header-menu"
            @select="handleMenuSelect"
          >
            <el-sub-menu
              v-for="group in menuGroups"
              :key="group.name"
              :index="group.name"
            >
              <template #title>
                <el-icon><component :is="group.icon" /></el-icon>
                <span>{{ group.title }}</span>
              </template>
              <el-menu-item
                v-for="route in group.routes"
                :key="route.path"
                :index="route.path"
                v-show="route.meta?.isHide !== '0'"
              >
                <el-icon v-if="route.meta?.icon">
                  <component :is="route.meta.icon" />
                </el-icon>
                <span>{{ route.meta?.title }}</span>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </nav>
        <div class="header-actions">
          <el-dropdown>
            <div class="user-info">
              <el-avatar :size="32" src="" />
              <span>{{ userInfo?.name || "用户" }}</span>
              <el-icon><CaretBottom /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleLogout"
                  >退出登录</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </header>

    <!-- 面包屑导航 -->
    <!-- <div class="breadcrumb-container" v-if="breadcrumbs.length > 0">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="(item, index) in breadcrumbs"
          :key="index"
          :to="item.path"
        >
          {{ item.name }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div> -->

    <!-- 下方内容区域 -->
    <main class="layout-main">
      <router-view />
    </main>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { CaretBottom } from "@element-plus/icons-vue";
import { useUserStore, useAppStore } from "@/stores";
import { ElMessage } from "element-plus";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const appStore = useAppStore();

const activeMenu = ref("");

// 获取需要在菜单中显示的路由分组（由动态路由自动生成）
const menuGroups = computed(() => {
  // 选择作为一级菜单的路由：有 children 的顶层路由
  const topLevelGroups = router
    .getRoutes()
    .filter(
      (r) =>
        r.children &&
        r.children.length > 0 &&
        r.meta?.title &&
        r.meta?.isHide !== "0"
    );

  const groups = topLevelGroups
    .map((r) => ({
      name: r.name as string,
      title: r.meta?.title as string,
      icon: r.meta?.icon as string,
      routes: (r.children || []).filter((c) => c.meta?.isHide !== "0"),
    }))
    .filter((g) => g.routes.length > 0);

  return groups;
});

const userInfo = computed(() => userStore.userInfo);
const breadcrumbs = computed(() => appStore.breadcrumbs);

// 面包屑更新函数
const updateBreadcrumbs = () => {
  const pathArray = route.path.split("/").filter((item) => item);
  const crumbs: Array<{ name: string; path?: string }> = [];

  let currentPath = "";
  pathArray.forEach((path) => {
    currentPath += `/${path}`;
    const matchedRoute = router.getRoutes().find((r) => r.path === currentPath);
    if (matchedRoute?.meta?.title) {
      crumbs.push({
        name: matchedRoute.meta.title as string,
        path: currentPath,
      });
    }
  });

  appStore.setBreadcrumbs(crumbs);
};

// 监听路由变化更新激活菜单
watch(
  () => route.path,
  (newPath) => {
    activeMenu.value = newPath;
    updateBreadcrumbs();
  },
  { immediate: true }
);

const handleMenuSelect = (index: string) => {
  router.push(index);
};

const handleLogout = () => {
  userStore.logout();
  ElMessage.success("退出登录成功");
  router.push("/auth/login");
};
</script>

<style lang="scss" scoped>
.layout-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.layout-header {
  background: #ffffff;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  height: 60px;
}

.logo {
  h1 {
    color: #409eff;
    font-size: 20px;
    font-weight: 600;
    margin: 0;
    white-space: nowrap;
  }
}

.navigation {
  flex: 1;
  margin-left: 32px;

  .header-menu {
    border-bottom: none;
    background: transparent;

    :deep(.el-menu-item) {
      border-bottom: 2px solid transparent;

      &:hover,
      &.is-active {
        background-color: #ecf5ff;
        border-bottom-color: #409eff;
      }
    }

    :deep(.el-sub-menu) {
      .el-sub-menu__title {
        border-bottom: 2px solid transparent;

        &:hover {
          background-color: #ecf5ff;
          border-bottom-color: #409eff;
        }
      }
    }
  }
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    background: #f5f7fa;
  }

  span {
    font-size: 14px;
    color: #606266;
  }
}

.breadcrumb-container {
  background: #ffffff;
  padding: 12px 24px;
  border-bottom: 1px solid #f0f0f0;

  :deep(.el-breadcrumb__item) {
    .el-breadcrumb__inner {
      color: #909399;

      &:hover {
        color: #409eff;
      }
    }

    &:last-child {
      .el-breadcrumb__inner {
        color: #303133;
        font-weight: 500;
      }
    }
  }
}

.layout-main {
  flex: 1;
  padding: 20px;
  background: #f5f5f5;
  overflow-y: auto;
}

// 响应式设计
@media (max-width: 1200px) {
  .header-content {
    padding: 0 16px;
  }

  .navigation {
    margin-left: 20px;
  }

  .logo h1 {
    font-size: 18px;
  }
}

@media (max-width: 768px) {
  .header-content {
    padding: 0 12px;
    height: 56px;
  }

  .navigation {
    margin-left: 12px;
  }

  .logo h1 {
    font-size: 16px;
  }

  .layout-main {
    padding: 16px 12px;
  }

  .breadcrumb-container {
    padding: 8px 12px;
  }
}
</style>
